package com.hcy.app.utils

import android.content.Context
import android.content.res.Configuration
import android.graphics.Point
import android.os.Build
import android.util.DisplayMetrics
import android.view.WindowManager

class ScreenInfoUtils {

    companion object {
        /**
         * 获取屏幕信息摘要
         */
        fun getScreenInfo(context: Context): String {
            return buildString {
                append("【物理分辨率】\n")
                append(getPhysicalResolution(context))
                append("\n\n【显示分辨率】\n")
                append(getDisplayResolution(context))
                append("\n\n【显示指标】\n")
                append(getDisplayMetrics(context))
                append("\n\n【屏幕特性】\n")
                append(getScreenFeatures(context))
            }
        }

        /**
         * 获取物理分辨率（硬件支持的最大分辨率）
         */
        private fun getPhysicalResolution(context: Context): String {
            val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                val windowMetrics = windowManager.currentWindowMetrics
                val bounds = windowMetrics.bounds
                "宽度: ${bounds.width()}px\n高度: ${bounds.height()}px"
            } else {
                val display = windowManager.defaultDisplay
                val size = Point()
                display.getRealSize(size)
                "宽度: ${size.x}px\n高度: ${size.y}px"
            }
        }

        /**
         * 获取显示分辨率（当前实际显示的分辨率）
         */
        private fun getDisplayResolution(context: Context): String {
            val displayMetrics = DisplayMetrics()
            val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                context.display?.getRealMetrics(displayMetrics)
            } else {
                @Suppress("DEPRECATION")
                windowManager.defaultDisplay.getMetrics(displayMetrics)
            }

            return """
                宽度: ${displayMetrics.widthPixels}px
                高度: ${displayMetrics.heightPixels}px
                状态栏高度: ${getStatusBarHeight(context)}px
                导航栏高度: ${getNavigationBarHeight(context)}px
            """.trimIndent()
        }

        /**
         * 获取显示指标
         */
        private fun getDisplayMetrics(context: Context): String {
            val metrics = context.resources.displayMetrics
            return """
                密度: ${metrics.density} (${getDensityName(metrics)})
                DPI: ${metrics.densityDpi}dpi
                缩放密度: ${metrics.scaledDensity}
                逻辑密度: ${metrics.xdpi} x ${metrics.ydpi}
            """.trimIndent()
        }

        /**
         * 获取屏幕特性
         */
        private fun getScreenFeatures(context: Context): String {
            val config = context.resources.configuration
            val screenLayout = config.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK

            return """
                屏幕方向: ${getOrientation(config.orientation)}
                屏幕尺寸分类: ${getScreenSizeName(screenLayout)}
                屏幕长宽比: ${getAspectRatio(context)}
                刷新率: ${getRefreshRate(context)}Hz
                HDR支持: ${hasHdrSupport(context)}
            """.trimIndent()
        }

        // 辅助方法
        private fun getStatusBarHeight(context: Context): Int {
            val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
            return if (resourceId > 0) context.resources.getDimensionPixelSize(resourceId) else 0
        }

        private fun getNavigationBarHeight(context: Context): Int {
            val resourceId = context.resources.getIdentifier("navigation_bar_height", "dimen", "android")
            return if (resourceId > 0) context.resources.getDimensionPixelSize(resourceId) else 0
        }

        private fun getDensityName(metrics: DisplayMetrics): String {
            return when (metrics.densityDpi) {
                DisplayMetrics.DENSITY_LOW -> "LDPI"
                DisplayMetrics.DENSITY_MEDIUM -> "MDPI"
                DisplayMetrics.DENSITY_HIGH -> "HDPI"
                DisplayMetrics.DENSITY_XHIGH -> "XHDPI"
                DisplayMetrics.DENSITY_XXHIGH -> "XXHDPI"
                DisplayMetrics.DENSITY_XXXHIGH -> "XXXHDPI"
                else -> "未知 (${metrics.densityDpi}dpi)"
            }
        }

        private fun getOrientation(orientation: Int): String {
            return when (orientation) {
                Configuration.ORIENTATION_LANDSCAPE -> "横向"
                Configuration.ORIENTATION_PORTRAIT -> "纵向"
                else -> "未定义"
            }
        }

        private fun getScreenSizeName(screenLayout: Int): String {
            return when (screenLayout) {
                Configuration.SCREENLAYOUT_SIZE_SMALL -> "小屏"
                Configuration.SCREENLAYOUT_SIZE_NORMAL -> "中屏"
                Configuration.SCREENLAYOUT_SIZE_LARGE -> "大屏"
                Configuration.SCREENLAYOUT_SIZE_XLARGE -> "超大屏"
                else -> "未知"
            }
        }

        private fun getAspectRatio(context: Context): String {
            val metrics = context.resources.displayMetrics
            val ratio = metrics.heightPixels.toFloat() / metrics.widthPixels
            return "%.2f:1 (${if (ratio > 1.9) "全面屏" else "标准屏"})".format(ratio)
        }

        private fun getRefreshRate(context: Context): Float {
            val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                windowManager.defaultDisplay.refreshRate
            } else {
                @Suppress("DEPRECATION")
                windowManager.defaultDisplay.refreshRate
            }
        }

        private fun hasHdrSupport(context: Context): Boolean {
            val display = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                context.display
            } else {
                @Suppress("DEPRECATION")
                (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
            }

            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                display?.hdrCapabilities != null
            } else {
                false
            }
        }

//        private fun hasUnderDisplayFingerprint(context: Context): Boolean {
//            return context.packageManager.hasSystemFeature("android.hardware.fingerprint")
//                    && context.resources.configuration.udfpsProps != null
//        }
    }
}